<template>
  <a-modal width="800px" :open="true" title="选择品牌" @cancel="onClose" @ok="onOk">
    <div class="search my ">
      <a-input v-model:value="keyword" placeholder="请输入品牌名称" style="width: 200px" :allowClear="true"/>
    </div>
    <div class="category" v-for="(cat, index) in categories" :key="index">
      <div class="title">{{ cat.name }}</div>
      <div class="brands">
        <div class="item" :class="crtItem == brand ? 'active':''" v-for="(brand, index) in cat.children" :key="index" @click="toSelect(brand)">
          <div class="logo">
            <img :src="getFile(brand.logo)" alt="">
          </div>
          <div class="name">{{ brand.name }}</div>
        </div>
      </div>
    </div>
  </a-modal>
</template>

<script setup>
import { ref, onMounted, computed,watch } from 'vue'
import { useGlobalStore } from '@/store/global';
import { getFile } from '@/api/att';
import { findIdxInArr } from '@/mixin';

const props = defineProps(['id'])
const emit = defineEmits(['close', 'select'])

const global = useGlobalStore()

const brands = ref([])
const crtItem = ref()
const keyword = ref('')

const categories = computed(() => {
  const arr = []

  brands.value.filter(i=>i.name.indexOf(keyword.value) >= 0).forEach(i => {
    const name = i.category
    if(props.id && i.id == props.id ){
      crtItem.value = i;
    }
    let idx = findIdxInArr(arr, i => i.name == name)

    if (idx < 0) {
      let item = { name, children: [i] }
      arr.push(item)
    } else {
      let item = arr[idx]
      item.children.push(i)
      arr[idx] = item
    }
  })

  return arr
})


onMounted(() => {
  load()
})

const toSelect = (item)=>{
  crtItem.value = item
}

const load = async () => {
  const res = await global.getBrands()
  brands.value = res || []
}

const onClose = () => {
  emit('close')
}
const onOk = ()=>{
  if(!crtItem.value ){
    message.warn('请先选择品牌')
    return 
  }
  emit('select',crtItem.value)
}
</script>

<style lang="less" scoped>
.category {
  .title {
    background-color: #efefef;
    padding: 4px 8px;
    margin-bottom: 12px;
  }

  .brands {
    overflow: hidden;

    .item {
      float: left;
      margin-right: 10px;
      margin-bottom: 10px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      border: 5px solid #aaa;      
      width: 80px;      
      text-align: center;
      cursor: pointer;
      overflow: hidden;
      border-radius: 8px;

      &:hover,
      &.active{
        border: 5px solid #1890ff;
      }

      img {
        border-radius: 8px 8px 0 0 ;
        width: 70px;
        margin-bottom: 8px;
      }
    }
  }
}
</style>